package com.yuns.course.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yuns.company.entity.CompanyDocRel;
import com.yuns.company.entity.CompanyInfoBase;
import com.yuns.company.entity.CompanyInfoBean;
import com.yuns.company.service.ICompanyDocRelService;
import com.yuns.company.service.ICompanyInfoBaseService;
import com.yuns.course.bean.*;
import com.yuns.course.entity.CourseBase;
import com.yuns.course.entity.CourseType;
import com.yuns.course.mapper.CourseTypeMapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yuns.course.service.ICourseTypeService;
import com.yuns.exam.entity.Exam;
import com.yuns.exam.entity.ExamQuestion;
import com.yuns.exam.entity.Question;
import com.yuns.exam.entity.QuestionOption;
import com.yuns.exam.service.IExamQuestionService;
import com.yuns.exam.service.IExamService;
import com.yuns.exam.service.IQuestionOptionService;
import com.yuns.exam.service.IQuestionService;
import com.yuns.exam.vo.ExamLibVo;
import com.yuns.study.entity.InfoDocI;
import com.yuns.study.entity.StudyVideoBase;
import com.yuns.study.service.IInfoDocIService;
import com.yuns.study.service.IStudyVideoBaseService;
import com.yuns.study.service.impl.InfoDocIServiceImpl;
import com.yuns.util.ImportExcelUtil;
import com.yuns.web.param.FrontPage;
import com.yuns.web.sys.param.BasePage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程类型基础表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-10-26
 */
@Service
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {

    @Resource
    private IInfoDocIService iInfoDocIService;

    @Resource
    private ICompanyDocRelService companyDocRelService;

    @Resource
    private IStudyVideoBaseService studyVideoBaseService;


    @Resource
    private IExamService examService;

    @Resource
    private IExamQuestionService examQuestionService;

    @Resource
    private IQuestionService questionService;

    @Resource
    private IQuestionOptionService questionOptionService;

    @Resource
    private ICompanyInfoBaseService companyInfoBaseService;


    @Override
    public List<CourseType> selectCourseTypeList(BasePage frontPage) {
        return baseMapper.selectCourseTypeList(frontPage);
    }

    @Override
    public List<CourseType> selectCourseTypeList(Page<CourseType> page, BasePage frontPage) {
        return baseMapper.selectCourseTypeList(page, frontPage);
    }

    /**
     * 文件导入(0:课程类型导入;1:法律法规导入;2:视频资料导入;3:题库;4:题目;5重点排污企业导入;6:警示教育企业导入)
     * @param type
     * @param file
     * @return
     */
    @Transactional
    @Override
    public Object importFile(Integer type, MultipartFile file) throws IOException {
        try {
            if (type == 0) {
                List<CourseTypeBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,CourseTypeBean.class);
                List<CourseType> list=new ArrayList<>();
                metaData.stream().filter(c->!"0".equals(c.getName())).forEach(item->{
                    CourseType courseType=new CourseType();
                    courseType.setName(item.getName());
                    courseType.setRemake(item.getRemake());
                    list.add(courseType);
                });
                this.insertBatch(list);
                return list;
            } else if (type == 1) {
                List<InfoDocIBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,InfoDocIBean.class);
                List<InfoDocI> list=new ArrayList<>();
                metaData.stream().filter(c->!"0".equals(c.getName())).forEach(item->{
                    InfoDocI infoDocI=new InfoDocI();
                    infoDocI.setName(item.getName());
                    infoDocI.setIntro(item.getIntro());
                    list.add(infoDocI);
                });
                iInfoDocIService.insertBatch(list);
                return list;
            }else if(type ==2){
                List<StudyVideoBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,StudyVideoBean.class);
                List<StudyVideoBase> list=new ArrayList<>();
                metaData.stream().filter(c->!"0".equals(c.getVideoName())).forEach(item->{
                    StudyVideoBase studyVideoBase=new StudyVideoBase();
                    studyVideoBase.setVideoName(item.getVideoName());
                    studyVideoBase.setVideoInfo(item.getVideoInfo());
                    studyVideoBase.setVideoIntegral(item.getVideoIntegral());
                    studyVideoBase.setPeriod(item.getPeriod());
                    list.add(studyVideoBase);
                });
                studyVideoBaseService.insertBatch(list);
                return list;
            }else if(type ==3){ // 题库
                List<ExamBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,ExamBean.class);
                System.out.println(metaData);
                List<Exam> examList = Lists.newArrayList();
                metaData.stream().filter(c->!"0".equals(c.getExamName())).forEach(item->{
                    Exam exam = Exam.builder().build();
                    exam.setQuestionSource(1); // 题库
                    exam.setExamName(item.getExamName());
                    exam.setExamRemark(item.getExamRemark());
                    examList.add(exam);
                });
                    examService.insertBatch(examList);

            }else if(type ==4){ // 题目
                // 查询题库
                FrontPage frontPage = new FrontPage();
                frontPage.set_search(false);
                List<ExamLibVo> examList = (List<ExamLibVo>) examService.selectExamList(frontPage);
                Map<String,List<ExamLibVo>> map = examList.stream().collect(Collectors.groupingBy(ExamLibVo::getExamName));

                List<QuestionBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,QuestionBean.class);

                metaData.stream().filter(c->!"0".equals(c.getQuestionType()) && c.getQuestionType()!=null).forEach(item->{
                    ExamQuestion t = ExamQuestion.builder().build();
                    Question t1 = Question.builder().build();
                    //查找题库
                    List<ExamLibVo> examLibVos = map.get(item.getExamName());
                    if(examLibVos!=null && examLibVos.size()>0){
                        String examid = String.valueOf(examLibVos.get(0).getExamId());
                        t.setExamId(examid);

                        t.setQuestionSource(1);
                        t1.setQuestionTitle(item.getQuestionTitle());
                        t.setQuestionTitle(item.getQuestionTitle());
                        t1.setAnalysis(item.getQuestionAnswer());
                        t.setAnalysis(item.getQuestionAnswer()); // 题目解析
                        t1.setQuestionTypeSel(item.getQuestionType());
                        t.setQuestionType(item.getQuestionType());
                        Integer grade = item.getQuestionType() == 0?2:
                                         item.getQuestionType() == 1?5:
                                         item.getQuestionType() == 2?2:
                                         item.getQuestionType() == 3?10:0;

                        t.setGrade(grade);
                        t1.setQuestionScore(grade);
                        if(item.getQuestionType() == 3) { //简答题
                            t.setQuestionAnswerReply(item.getQuestionOptionA());
                            t1.setQuestionAnswerReply(item.getQuestionOptionA());
                        }else {

                            t.setQuestionAnswer(item.getQuestionOptionARightAnswer());
                            t1.setQuestionAnswer(item.getQuestionOptionARightAnswer());
                        }
                        t1.setQuestionType(1);// 题目类型  0：岗位职责   1：问病荐药  2：综合练习
                        questionService.insert(t1);
                        t.setQuestionId(String.valueOf(t1.getId()));
                        examQuestionService.insert(t);
                        List<QuestionOption> questionOptions = Lists.newArrayList();
                        if(item.getQuestionType() == 0 || item.getQuestionType()==1 || item.getQuestionType()==2) {
                            for (int i = 0; i < 4; i++) {
                                if(item.getQuestionType()==2 && i == 2) {
                                   break;
                                }
                                String code = i == 0 ? "A" :
                                        i == 1 ? "B" :
                                                i == 2 ? "C" :
                                                        i == 3 ? "D" : "A";
                                String content = i == 0 ? item.getQuestionOptionA() :
                                        i == 1 ? item.getQuestionOptionB() :
                                                i == 2 ? item.getQuestionOptionC() :
                                                        i == 3 ? item.getQuestionOptionD() : "A";
                                QuestionOption questionOption = QuestionOption.builder().build();
                                questionOption.setCode(code);
                                questionOption.setQuestionId(String.valueOf(t1.getId()));
                                questionOption.setContent(content);
                                questionOptions.add(questionOption);
                            }

                            questionOptionService.insertBatch(questionOptions);
                        }
                    }
                });
            }else if(type ==5 || type==6 ){
                List<CompanyInfoBean> metaData = new ImportExcelUtil().parseFromExcel(file.getInputStream(),3,CompanyInfoBean.class);
                List<CompanyInfoBase> list=new ArrayList<>();
                metaData.stream().filter(c->!"0".equals(c.getCompanyName())).forEach(item->{
                    CompanyInfoBase base=new CompanyInfoBase();
                    base.setCompanyName(item.getCompanyName());
                    if(!"0".equals(item.getPulishTime()) && !"".equals(item.getPulishTime())){
                        base.setPulishTime(item.getPulishTime());
                    }
                    if(!"0".equals(item.getDealTime()) && !"".equals(item.getDealTime())){
                        base.setDealTime(item.getDealTime());
                    }
                    if(!"0".equals(item.getPulishNo()) && !"".equals(item.getPulishNo())){
                        base.setPulishNo(item.getPulishNo());
                    }
                    if(!"0".equals(item.getAddress()) && !"".equals(item.getAddress())){
                        base.setAddress(item.getAddress());
                    }
                    if(!"0".equals(item.getPersonName()) && !"".equals(item.getPersonName())){
                        base.setPersonName(item.getPersonName());
                    }
                    base.setCompanyType(type==5?0:1);//企业类型
                    list.add(base);
//                    String[] infoDocs=item.getInfoDocs().split(",");
//                    if (flag && !"0".equals(item.getPersonName())){
//                        this.intoCompanyUserRel(base.getId(),infoDocs);
//                    }
                });
                companyInfoBaseService.insertBatch(list);
                return list;
            }
        }catch (Exception e){
//            new RuntimeException("文件导入失败");
            e.printStackTrace();
            throw e;

        }
        return null;
    }

    /**
     * 根据法律法规名称插入到关联表中
     * @param companyId
     * @param names
     */
    public void intoCompanyUserRel(Integer companyId,String[] names){
        List<InfoDocI> list=iInfoDocIService.selectList(null);
        List<CompanyDocRel> rels=new ArrayList<>();
        for (String name:names ) {
            for (InfoDocI i:list ) {
                if(name.equals(i.getName())){
                    CompanyDocRel rel=new CompanyDocRel();
                    rel.setCompanyId(companyId);
                    rel.setDocId(i.getId());
                    rels.add(rel);
                    continue;
                }
            }
        }
        companyDocRelService.insertBatch(rels);
    }
}
